package Phase;

import StateInformation.GameState;
import World.Application;
import java.util.ArrayList;

public class ArkanoidController {

    private GameState gameState;
    private ArrayList<String> world;
    private ArkanoidPanel arkanoidPanel;
    private Application application;

    public ArkanoidController(ArrayList world, ArkanoidPanel arkanoidPanel, Application application) {
        this.world = world;
        this.arkanoidPanel = arkanoidPanel;
        this.application = application;
        gameState = new GameState(arkanoidPanel);
        gameState.setWorld(world);
    }

    public ArkanoidController(ArkanoidPanel arkanoidPanel, Application application) {
        this.arkanoidPanel = arkanoidPanel;
        this.application = application;
        GameStateSaver gameStateSaver = new FileGameStateSaver();
        gameState = gameStateSaver.load("prueba");
        if (gameState == null){
            application.createNewArkanoidController();
            return;
        }
        world = gameState.getWorld();
    }

    public void execute() {
        if (world.size() > 0) {
            if (!gameState.getFinalLevel().equals("")) {
                PhaseController phaseController = new PhaseController(gameState.getFinalLevel(), arkanoidPanel, gameState, this);
                application.addKeyListener(phaseController);
                gameState.setWorld(world);
                phaseController.execute();
            } else {
                PhaseController phaseController = new PhaseController(world.get(0), arkanoidPanel, gameState, this);
                application.addKeyListener(phaseController);
                phaseController.execute();
                gameState.setFinalLevel(world.get(0));
                world.remove(0);
            }
            saveState();
        } else {
            gameOver();
        }
    }

    public void phaseFinished(PhaseController phaseController) {
        saveState();
        execute();
    }

    public Application getApplication() {
        return application;
    }

    public void gameOver() {
        arkanoidPanel.setVisible(false);
        application.returnMainMenu();
    }

    public void ballLost() {
        saveState();
    }

    private void saveState() {
        //if (!gameState.getUser().getName().equals("")) {
            gameState.setWorld(world);
            GameStateSaver gameSaver = new FileGameStateSaver();
            gameSaver.save(gameState, gameState.getUser().getName());
        //}
    }
}
